﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class Demo : MonoBehaviour
{
    public Button playBtn;

    public Button pullBtn;
    public Button pushBtn;

    public InputField titleInputField;

    public VideoPlayer videoPlayer;
    public RawImage rawImage;

    string videoPath = "";

    // Start is called before the first frame update
    void Start()
    {
        playBtn.onClick.AddListener(PlayVideo);

        pullBtn.onClick.AddListener(PullVideo);
        pushBtn.onClick.AddListener(PushVideo);


        videoPath = Path.Combine(Application.streamingAssetsPath, "def.mp4");

    }

    void PlayVideo()
    {
        Debug.Log("Unity 播放视频 ");

        if (File.Exists(videoPath))
        {
            Debug.Log("Unity 存在路径 222  " + videoPath);
        }

        videoPlayer.url = videoPath;
        videoPlayer.playOnAwake = false;
        videoPlayer.waitForFirstFrame = true;
        videoPlayer.sendFrameReadyEvents = true;
        videoPlayer.frameReady += GenerateCoverImg;
        videoPlayer.Play();

    }


    string curVideoId;
    string curImageUrl;

    void PullVideo()
    {
        Debug.Log("Unity 下拉视频 ");

        Dictionary<string, string> posFields = new Dictionary<string, string>
        {
            {"user_name", "c000000001"},
            {"title", "白菜"},
            {"sub_title", "默认子标题"},
            {"keyword", "default"},
            {"category_1", "0"},
            {"category_2", "0"},

            {"category_3", "0"},
            {"completeState", "1"},
            {"isserial", "0"},
            {"author_name", "作者"},
            {"booksynopsis", "测试测试"},

            {"cover", curImageUrl},
            {"tags", "默认"},
            {"is_public", "1"},
            {"chapter_fanwai", "0"},
            {"is_chapter", "1"},
            {"chapter_url", curVideoId}
        };
        string backUrl = @"https://api.cavefire.com/vod/create";
        BestHttpUtil.Instance.SendHTTPPostRequestWithCallBack(backUrl, posFields, (string dataStr) =>
        {
            Debug.Log("Unity 视频发送成功, 通知应用服务器: dataStr= " + dataStr);

            //Response_General<OSSResModel> response = JsonUtility.FromJson<Response_General<OSSResModel>>(dataStr);

        });
    }

    void PushVideo()
    {
        Debug.Log("Unity 上传视频 ");

        string userId = "c000000001";
        string title = titleInputField.text;
        string desc = "这是个大白菜";
        string cateId = "23";
        string tags = "56";
        videoPath = Path.Combine(Application.streamingAssetsPath, "def.mp4");
        string coverImgPath = Path.Combine(Application.persistentDataPath, "def.jpg");

        AliyunVodHelper.Instance.PushVideoBySTS(
            userId,
            title,
            desc,
            cateId,
            tags,
            videoPath,
            coverImgPath,
            PushSucessed
        );

    }

    void PushSucessed(string str)
    {
        string[] temp = str.Split('_');
        string videoId = temp[0];
        string imageUrl = temp[1];
        //Debug.Log("Unity videoId= " + videoId + ";  imageUrl= " + imageUrl);

        curImageUrl = imageUrl;
        curVideoId = videoId;

    }

    int curFrameValue = 0;
    void GenerateCoverImg(VideoPlayer source, long frameIdx)
    {
        curFrameValue++;
        if (curFrameValue == 1)
        {
            Texture2D videoFrameTex;
            RenderTexture renderTex = source.texture as RenderTexture;
            videoFrameTex = new Texture2D(renderTex.width, renderTex.height);
            RenderTexture.active = renderTex;
            videoFrameTex.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
            videoFrameTex.Apply();
            RenderTexture.active = null;
            source.frameReady -= GenerateCoverImg;
            source.sendFrameReadyEvents = false;

            string coverImgPath = Path.Combine(Application.persistentDataPath, "def.jpg");
            Debug.Log("Unity_   frameIdx= " + frameIdx + "; coverImgPath= " + coverImgPath);

            File.WriteAllBytes(coverImgPath, videoFrameTex.EncodeToJPG());

        }
    }

}
